""" -*- coding: utf-8 -*-"""
from flask import Blueprint, request, jsonify, g, current_app
from werkzeug.utils import secure_filename
import os
from models import db, Project, FileType, File
from extends.auth import require_role
from extends.file_handler import allowed_file, generate_filename, get_project_file_path

file_bp = Blueprint('file', __name__)


@file_bp.route('/projects/<int:project_id>/files', methods=['POST'], url_prefix='/files')
@require_role('designer')  # 设计师和项目助理可上传文件
def upload_file(project_id):
    """上传项目文件"""
    # 验证项目是否存在
    project = Project.query.get(project_id)
    if not project:
        return jsonify({'error': 'Project not found'}), 404

    # 检查文件是否在请求中
    if 'file' not in request.files:
        return jsonify({'error': 'No file part'}), 400

    file = request.files['file']
    if file.filename == '':
        return jsonify({'error': 'No selected file'}), 400

    # 检查文件扩展名
    if not allowed_file(file.filename):
        extensions = ', '.join(current_app.config['ALLOWED_EXTENSIONS'])
        return jsonify({'error': f'Invalid file type. Allowed types: {extensions}'}), 400

    # 获取表单数据
    file_type_id = request.form.get('file_type_id')
    if not file_type_id:
        return jsonify({'error': 'Missing file type ID'}), 400

    # 验证文件类型是否存在
    file_type = FileType.query.get(file_type_id)
    if not file_type:
        return jsonify({'error': 'File type not found'}), 404

    # 获取设计阶段名称
    design_phase_name = file_type.design_phase.name if file_type.design_phase else 'General'

    # 生成安全文件名
    original_filename = secure_filename(file.filename)
    new_filename = generate_filename(
        project.project_number,
        design_phase_name,
        file_type.name,
        g.current_user.name,
        original_filename
    )

    # 获取保存路径
    save_path = get_project_file_path(project.project_number, design_phase_name)
    file_path = os.path.join(save_path, new_filename)

    # 保存文件
    os.makedirs(os.path.dirname(file_path), exist_ok=True)
    file.save(file_path)

    # 创建文件记录
    new_file = File(
        project_id=project_id,
        file_type_id=file_type_id,
        user_id=g.current_user.id,
        file_path=file_path,
        original_filename=original_filename
    )

    try:
        db.session.add(new_file)
        db.session.commit()
        return jsonify({
            'message': 'File uploaded successfully',
            'file': new_file.to_dict()
        }), 201
    except Exception as e:
        # 如果保存失败，删除已上传的文件
        if os.path.exists(file_path):
            os.remove(file_path)
        db.session.rollback()
        return jsonify({'error': f'Database error: {str(e)}'}), 500


@file_bp.route('/download/<int:file_id>', methods=['GET'])
def download_file(file_id):
    """下载文件"""
    file_record = File.query.get(file_id)
    if not file_record:
        return jsonify({'error': 'File not found'}), 404

    # 检查文件是否存在
    if not os.path.exists(file_record.file_path):
        return jsonify({'error': 'File does not exist on server'}), 404

    # 在实际应用中，这里应该返回文件内容
    # 简化版：返回文件路径
    return jsonify({
        'file_path': file_record.file_path,
        'original_filename': file_record.original_filename
    })